package tunnel

import (
	"fmt"
	"internal-net-bridge-server/internal/tunnel/protocols/http"
	"log"
	"net"
	"strconv"
	"time"

	"internal-net-bridge-server/internal/models"
	"internal-net-bridge-server/internal/services"
	"internal-net-bridge-server/internal/tunnel/protocols/common"
)

// ========================================
// 隧道管理器核心业务逻辑
// ========================================
// 本文件包含隧道管理器的核心CRUD和配置管理功能
// 数据结构定义在 types.go
// 具体功能实现分散在各个专门的模块文件中

// NewTunnelManager 创建新的隧道管理器
func NewTunnelManager(tunnelService *services.TunnelService) *TunnelManager {
	tm := &TunnelManager{
		tunnels:             make(map[string]*models.Tunnel),
		portMappings:        make(map[string]*models.Tunnel),
		domainMappings:      make(map[string]*models.Tunnel),
		connectionMap:       make(map[string]*StreamingConnection),
		responseAssembly:    make(map[string]*ResponseAssembly),
		newChunkedResponses: make(map[string]*NewChunkedResponse),
		responseMetadata:    make(map[string]*ResponseMetadata),   // 🔥 响应元数据
		rateLimiters:        make(map[string]*common.RateLimiter), // 🔥 限速器缓存
		canceledRequests:    make(map[string]bool),
		loggedWarnings:      make(map[string]time.Time),
		tunnelPort:          9001, // 与客户端配置匹配
		tunnelService:       tunnelService,
		dnsService:          nil,
		domainRouter:        nil,
		streamingHandler:    nil,
		proxyAdapter:        nil,
		protocolListeners:   make(map[string]interface{}),   // 🔥 协议监听器映射
		http2Handler:        http.NewHTTP2ResponseHandler(), // 🚀 HTTP/2响应处理器
	}

	// ⚠️ 旧的TCP隧道功能已废弃
	// tm.streamingHandler = NewStreamingHandler(tm) // 已删除
	// go tm.startConnectionCleaner() // 已删除

	// 🔥 启动取消请求清理协程
	go tm.cleanupCanceledRequests()

	// 🚀 启动HTTP/2响应清理定时器（每30秒清理一次）
	tm.http2Handler.StartCleanupTimer(30 * time.Second)
	log.Printf("✅ [TunnelManager] HTTP/2响应处理器已启动")

	return tm
}

// GetHTTP2Handler 获取HTTP/2响应处理器
func (tm *TunnelManager) GetHTTP2Handler() *http.HTTP2ResponseHandler {
	return tm.http2Handler
}

// LoadActiveTunnels 从数据库加载所有active状态的隧道到内存
// 这个方法应该在服务器启动时调用，确保客户端连接时能找到对应的隧道
func (tm *TunnelManager) LoadActiveTunnels() error {
	if tm.tunnelService == nil {
		return fmt.Errorf("tunnelService未设置")
	}

	// 从数据库获取所有active状态的隧道
	tunnelMappings, err := tm.tunnelService.GetAllActiveTunnelMappings()
	if err != nil {
		return fmt.Errorf("从数据库加载隧道失败: %v", err)
	}

	loadedCount := 0
	for _, tunnelMapping := range tunnelMappings {
		// 创建Tunnel对象
		tunnel := &models.Tunnel{
			ID:                tunnelMapping.TunnelID,
			LocalHost:         tunnelMapping.LocalIP,
			LocalPort:         fmt.Sprintf("%d", tunnelMapping.LocalPort),
			PublicPort:        fmt.Sprintf("%d", tunnelMapping.PublicPort),
			TunnelPool:        nil, // 连接池会在客户端连接时创建
			RequestMap:        make(map[string]*models.HTTPRequest),
			HTTPConnectionMap: make(map[string]net.Conn),
		}

		// 添加到tunnels map
		tm.mutex.Lock()
		tm.tunnels[tunnel.ID] = tunnel
		tm.portMappings[tunnel.PublicPort] = tunnel
		tm.mutex.Unlock()

		loadedCount++
		log.Printf("✅ 已加载隧道: %s (端口: %s)", tunnel.ID[:8], tunnel.PublicPort)

		// 🔥 启动公共端口监听器
		publicPort, _ := strconv.ParseInt(tunnel.PublicPort, 10, 64)
		if err := tm.StartPublicPortListenerForTunnelID(tunnel.ID, publicPort); err != nil {
			log.Printf("⚠️  启动公共端口监听器失败: tunnelID=%s, port=%s, error=%v",
				tunnel.ID[:8], tunnel.PublicPort, err)
		} else {
			log.Printf("✅ 公共端口监听器已启动: tunnelID=%s, port=%s", tunnel.ID[:8], tunnel.PublicPort)
		}
	}

	log.Printf("✅ 从数据库加载了 %d 个active隧道", loadedCount)
	return nil
}

// ========================================
// CreateTunnel, DeleteTunnel, Get*/Find* 等核心CRUD方法
// 已移至 manager_core_methods.go
// ========================================

// ListTunnels 列出所有隧道
func (tm *TunnelManager) ListTunnels() []*models.Tunnel {
	tm.mutex.RLock()
	defer tm.mutex.RUnlock()

	tunnels := make([]*models.Tunnel, 0, len(tm.tunnels))
	for _, tunnel := range tm.tunnels {
		tunnels = append(tunnels, tunnel)
	}
	return tunnels
}

// GetTunnel 获取指定隧道
func (tm *TunnelManager) GetTunnel(tunnelID string) (*models.Tunnel, bool) {
	tm.mutex.RLock()
	defer tm.mutex.RUnlock()

	tunnel, exists := tm.tunnels[tunnelID]
	return tunnel, exists
}

// InitializeWithConfig 使用配置初始化隧道管理器
func (tm *TunnelManager) InitializeWithConfig(config *models.AppConfig) error {
	// 简化实现
	return nil
}

// SetDomainRouter 设置域名路由服务
func (tm *TunnelManager) SetDomainRouter(domainRouter *services.DomainRouter) {
	tm.mutex.Lock()
	defer tm.mutex.Unlock()
	tm.domainRouter = domainRouter
}

// GetDomainRouter 获取域名路由服务
func (tm *TunnelManager) GetDomainRouter() *services.DomainRouter {
	tm.mutex.RLock()
	defer tm.mutex.RUnlock()
	return tm.domainRouter
}

// StartTunnelServer 启动隧道服务器（委托给 server.go 中的 Start 方法）
func (tm *TunnelManager) StartTunnelServer() {
	// 使用端口 9001（与客户端配置匹配）
	if err := tm.Start(9001); err != nil {
		panic(err)
	}
}
